package com.doyens.reggie.controller;

import com.doyens.reggie.commons.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String path;//null

    // 文件上传接口
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws Exception{//a.png  b.jpg
        // 获取上传的文件名
        String filename = file.getOriginalFilename();
        filename = UUID.randomUUID().toString()+filename;

        // 保证path一定存在
        File f = new File(path);
        if(!f.exists()){
            //创建这个目录
            f.mkdirs();
        }

        // 将图片存到服务器中 D:imgs
        file.transferTo(new File(path + filename));
        return R.success(filename);
    }

    // 文件下载接口
    @GetMapping("download")
    public void download(String name, HttpServletResponse response) throws Exception{
        // 告诉浏览器 我给你响应的是图片
        response.setContentType("image/jpeg");
        ServletOutputStream os = response.getOutputStream();
        // 去哪里下载 path:d://img//a.png
        FileInputStream fis = new FileInputStream(path + name);
        byte[] bytes = new byte[1024];
        int len=0;
        while ((len = fis.read(bytes)) != -1){
            os.write(bytes,0,len);
        }

        fis.close();
    }

}
